package com.xj.jdk17.methodhandle;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * jdk1.7 新添加方法句柄例子
 * User: xia
 * Date: 13-10-26
 * Time: 下午6:39
 */
public class Demo {
    public String getxx() throws Throwable {
        /*MethodType mt = MethodType.methodType(boolean.class, Object.class);
        List<String> list = new ArrayList<String>();
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        MethodHandle handle = lookup.findVirtual(ArrayList.class, "add", mt);
        boolean boo = (Boolean) handle.invoke(list, "xia");
        System.out.println(boo + " " + list.get(0));
        handle = handle.bindTo(list);
        handle.invoke("jun");//可以不要返回值
        System.out.println(list.size());*/
        return "公司";
    }

    public int getAge() {
        return 45;
    }

    public Bean getBean() {
        Bean b = new Bean();
        b.setAge(12);
        b.setMoney(122.8f);
        b.setName("张三");
        return b;
    }

    /**
     * 批量递归转换对象为string
     *
     * @param obj
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public String invokeGetInfo(Object obj) {
        Class clazz = obj.getClass();
        Method[] methods = clazz.getDeclaredMethods();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < methods.length; i++) {
            Method m = methods[i];
            String name = m.getName();
            if (name.indexOf("get") == 0) {
                Object res = null;
                try {
                    res = m.invoke(obj);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                if (res != null) {
                    String className = res.getClass().getPackage().getName();
                    if (className.equals("java.lang")) {
                        sb.append(name.substring(3, name.length()).toUpperCase() + " = ");
                        sb.append(res.toString() + ";\n");
                    } else {
                        sb.append(name.substring(3, name.length()).toUpperCase() + " =\n{\n");
                        sb.append(invokeGetInfo(res));
                        sb.append(" }\n");
                    }
                }
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) throws Throwable {
        Demo d = new Demo();
        System.out.println(d.invokeGetInfo(d));
    }
}
